<?php

namespace App\Http\Controllers\Backend;

use App\Models\WechatGroup;
use Illuminate\Http\Request;
use Overtrue\LaravelWeChat\Facade;

/**
 * Class WechatMenuApplicationController
 * @package App\Http\Controllers\Backend
 * 应用微信菜单
 */
class WechatMenuApplicationController extends BackendController
{
    /**
     * @param Request $request
     * @return array|bool
     * 应用微信公众号菜单
     */
    public function store(Request $request)
    {
        $app = Facade::officialAccount();
        $menu = WechatGroup::findOrFail($request->group_id);
        if(!$menu->is_enable){
            // 停用
            $buttons = [];
        }else{
            // 启用
            $buttons = $menu->assembleAppliedMenus();
        }
        $delMenuResponse = $app->menu->delete();
        if ($delMenuResponse['errcode'] == 0) {
            if (empty($buttons)) {
                return $delMenuResponse;
            }
            $createMenuResponse = $app->menu->create($buttons);
            if ($createMenuResponse['errcode'] == 0) {
                return $createMenuResponse;
            } else {
                $errorMsg = $createMenuResponse['errmsg'];
            }
        } else {
            $errorMsg = $delMenuResponse['errmsg'];
        }
        return $this->fail($errorMsg);
    }
}
